package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * projectName: tingshu-parent
 *
 * @author: 王宝贵
 * time: 2024/10/22 20:45 周二
 * description:
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Autowired
    private MinioClient MinioClient;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        // 捅是否存在
        boolean found =
                MinioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        if (!found) {
            // M不存在就创建
            MinioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        } else {
            System.out.println("捅存在");
        }

        //ceshi/都市修炼之美人图鉴.jpg
        String data = "/" + DateUtil.today() + "/";
        String objectName = UUID.randomUUID().toString().replaceAll("-", "");
        //获取文件的的后缀
        objectName = data + objectName + "." + FileUtil.extName(file.getOriginalFilename());

        /**
         * bucket(String bucketName): 指定存储桶的名称。
         * object(String objectName): 指定存储对象的名称。
         * stream(InputStream stream, long length, long partSize): 指定文件的输入流、文件大小以及分块大小（-1表示使用默认值）。
         * contentType(String contentType): 指定文件的MIME类型。
         */
        MinioClient.putObject(
                PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(objectName).stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());

        //文件名字 ip加文件后缀
        String url = minioConstantProperties.getEndpointUrl() + "/" +minioConstantProperties.getBucketName()+ objectName;
        return url;
    }

}